<template>
    <div>
        <el-card>
            <el-form :inline="true" class="btn">
                <el-form-item label="用户名">
                    <el-input placeholder="输入用户名" v-model="keyWord"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="keyWord ? false : true" @click="search">搜索</el-button>
                    <el-button type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card style="margin: 10px 0;">
            <el-button type="primary" @click="addUser">添加用户</el-button>
            <el-button type="warning" :disabled="!selectDeleteUsers.length" @click="deleteUsers">批量删除</el-button>

            <el-table style="margin: 10px 0;" border :data="userInfo" @selection-change="selectChange">
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="ID" prop="id"></el-table-column>
                <el-table-column label="用户名字" prop="username"></el-table-column>
                <el-table-column label="用户名称" prop="name"></el-table-column>
                <el-table-column label="用户角色" prop="roleName"></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180px"></el-table-column>
                <el-table-column label="更新时间" prop="updateTime" width="180px"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template #="{ row, $index }">
                        <el-button type="primary" icon="User" size="small" @click="setRole(row)">分配角色</el-button>
                        <el-button type="warning" icon="Edit" size="small" @click="eidtUser(row)">编辑</el-button>
                        <el-button type="danger" icon="Delete" size="small" @click="deleteUser(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 7]"
                :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
                @size-change="handleSizeChange" @current-change="getUserInfo" />

            <el-drawer v-model="drawer">
                <template #header>
                    <h4>{{ userParams.id ? "更新用户" : "添加用户" }}</h4>
                </template>
                <template #default>
                    <el-form :model="userParams" :rules="rules" ref="userForm">
                        <el-form-item label="用户姓名" prop="username">
                            <el-input placeholder="输入用户姓名" v-model="userParams.username"></el-input>
                        </el-form-item>

                        <el-form-item label="用户昵称" prop="name">
                            <el-input placeholder="输入用户昵称" v-model="userParams.name"></el-input>
                        </el-form-item>

                        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                            <el-input placeholder="输入用户密码" v-model="userParams.password"></el-input>
                        </el-form-item>
                    </el-form>
                </template>

                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="cancelClick">取消</el-button>
                        <el-button type="primary" @click="confirmClick">确定</el-button>
                    </div>
                </template>
            </el-drawer>

            <el-drawer v-model="drawer1">
                <template #header>
                    <h4>分配角色</h4>
                </template>
                <template #default>
                    <el-form :model="userParams" :rules="rules" ref="userForm">
                        <el-form-item label="用户姓名" prop="username">
                            <el-input v-model="userParams.username" :disabled="true"></el-input>
                        </el-form-item>

                        <el-form-item label="职位列表" prop="name">
                            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                                @change="handleCheckAllChange">全选</el-checkbox>
                            <el-checkbox-group v-model="userRole" @change="handleCheckedRolesChange">
                                <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role"
                                    :value="role">{{
                role.roleName
            }}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>
                </template>

                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="drawer1= false">取消</el-button>
                        <el-button type="primary" @click="confirmRoleClick">确定</el-button>
                    </div>
                </template>
            </el-drawer>
        </el-card>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqUser, reqAddOrUpdateUser, reqAllRole, reqSetUserRole, reqDeleteUser, reqDeleteSomeUser } from '@/api/acl/user'
import { ElMessage } from 'element-plus';
import useLayoutSettingStore from '@/store/modules/setting'
const pageNo = ref(1)
const pageSize = ref(3)
const total = ref(0)
const userInfo = ref([])
const drawer = ref(false)
const drawer1 = ref(false)
const userForm = ref()
const checkAll = ref(false)
const allRole = ref([])
const userRole = ref([])
const isIndeterminate = ref(true)
const selectDeleteUsers = ref([])
const keyWord = ref('')
const settingStore=useLayoutSettingStore()
const userParams = reactive({
    username: '',
    name: '',
    password: ''
})

onMounted(() => {
    getUserInfo()
})

const getUserInfo = async (page = 1) => {
    pageNo.value = page
    const res = await reqUser(pageNo.value, pageSize.value, keyWord.value)
    if (res.code == 200) {
        total.value = res.data.total
        userInfo.value = res.data.records
    }
}

const addUser = () => {
    drawer.value = true
    nextTick(() => {
        userForm.value.resetFields()
        Object.assign(userParams, {
            id: 0,
            username: '',
            name: '',
            password: ''
        })
    })
}

const eidtUser = (row) => {
    drawer.value = true
    nextTick(() => {
        userForm.value.resetFields()
        Object.assign(userParams, row)
    })
}

const confirmClick = async () => {
    await userForm.value.validate()
    const res = await reqAddOrUpdateUser(userParams)
    if (res.code == 200) {
        drawer.value = false
        ElMessage({ type: 'success', message: userParams.id ? '更新成功' : '添加成功' })
        // getUserInfo()
        window.location.reload()
    } else {
        ElMessage({ type: 'error', message: userParams.id ? '更新失败' : '添加失败' })
    }
}

const cancelClick = () => {
    drawer.value = false
}

const setRole = async (row) => {
    Object.assign(userParams, row)
    const res = await reqAllRole(userParams.id)
    if (res.code == 200) {
        allRole.value = res.data.allRolesList
        userRole.value = res.data.assignRoles
        drawer1.value = true
    }
}
const handleCheckAllChange = (val) => {
    userRole.value = val ? allRole.value : []
    isIndeterminate.value = false
}

const handleCheckedRolesChange = (value) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === allRole.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}

const confirmRoleClick = async () => {
    const data = {
        userId: userParams.id,
        roleIdList: userRole.value.map(item => item.id),
    }
    const res = await reqSetUserRole(data)
    if (res.code == 200) {
        ElMessage({ type: 'success', message: '分配职务成功' })
        drawer1.value = false
        getUserInfo(pageNo.value)
    }
}

const deleteUser = async (id) => {
    const res = await reqDeleteUser(id)
    if (res.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getUserInfo(userInfo.value.length > 1 ? pageNo.value : pageNo.value - 1)
    }
}

const selectChange = (value) => {
    selectDeleteUsers.value = value
}

const deleteUsers = async () => {
    const idList = selectDeleteUsers.value.map(item => item.id)
    const res = await reqDeleteSomeUser(idList)
    if (res.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getUserInfo(pageNo.value)
    }
}

const search = () => {
    getUserInfo()
    keyWord.value = ''
}
const reset = () => {
    settingStore.refresh=!settingStore.refresh
}
const rules = {
    username: [{ required: true, trigger: 'blur' }],
    name: [{ required: true, trigger: 'blur' }],
    password: [{ required: true, trigger: 'blur' }],
}
</script>

<style scoped>
.btn {
    display: flex;
    justify-content: space-between;
    align-items: center
}
</style>